import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { fromJS } from 'immutable'

import moment from 'moment'

import { intl } from '../../../intl/intl'
import { formatContractPriceDecimal, formatDecimal, formatValue } from '../../../utils/dataUtils'
import Pagination from '../../../component/pagination/Pagination'
import Loading from '../../../component/loading/Loading'
import themeHOC from '../../common/themeHOC'

import { pollHistoryOrder, setHistoryOrderEnabled } from '../../../redux/actions/tradeDataQueryAction'

@connect((state) => {
  return {
    currentContract: state.trade.market.get('currentContract'),
    contracts: state.trade.market.get('contracts'),
    historyOrderCurrentPage: state.trade.dataQuery.get('historyOrderCurrentPage'),
    historyOrderTotalPage: state.trade.dataQuery.get('historyOrderTotalPage'),
    historyOrderLoading: state.trade.dataQuery.get('historyOrderLoading'),
    historyOrderList: state.trade.dataQuery.get('historyOrderList')
  }
}, (dispatch) => {
  return bindActionCreators({
    pollHistoryOrder
  }, dispatch)
})
@themeHOC
class HistoryOrder extends Component {
  componentDidMount () {
    const { currentContract, pollHistoryOrder } = this.props
    pollHistoryOrder(currentContract, 1)
  }

  componentDidUpdate (prevProps, prevState, snapshot) {
    const { currentContract, pollHistoryOrder } = this.props
    if (formatValue(prevProps.currentContract, 'InstrumentID') !== formatValue(currentContract, 'InstrumentID')) {
      pollHistoryOrder(currentContract, 1)
    }
  }

  componentWillUnmount () {
    setHistoryOrderEnabled(false)
  }

  renderTableContent () {
    const { contracts, historyOrderList } = this.props
    return historyOrderList.map((order, index) => {
      const id = formatValue(order, 'InstrumentID')
      const contract = formatValue(contracts, id, fromJS({}))
      const isInverse = formatValue(contract, 'IsInverse', 0)
      const volumeMultiple = formatValue(contract, 'VolumeMultiple', 1)
      const isBuy = formatValue(order, 'Direction') === 48
      const buySell = isBuy ? 'buy' : 'sell'
      const isOpen = formatValue(order, 'OffsetFlag') === '0'
      const tradeVolume = formatValue(order, 'VolumeTraded', 0)
      const turnover = formatValue(order, 'Turnover')
      const averagePrice = isInverse ? tradeVolume * volumeMultiple / turnover : turnover / tradeVolume / volumeMultiple
      return (
        <tr key={`history_order_${index}`}>
          <td>{id}</td>
          <td
            datatype={buySell}>
            {
              isOpen
                ? (isBuy ? intl('buy_open_long') : intl('sell_open_short'))
                : (isBuy ? intl('buy_close_short') : intl('sell_close_long'))
            }
          </td>
          <td>
            {moment(formatValue(order, 'InsertTime') * 1000).format('YYYY-MM-DD hh:mm:ss')}
          </td>
          <td>{formatValue(order, 'Volume')}</td>
          <td>{formatContractPriceDecimal(contract, formatValue(order, 'LimitPrice'))}</td>
          <td>{tradeVolume}</td>
          <td>{tradeVolume === 0 ? '--' : formatContractPriceDecimal(contract, averagePrice)}</td>
          <td>{formatDecimal(formatValue(order, 'CloseProfit'), 8)}</td>
          <td>{formatDecimal(formatValue(order, 'Fee'), 8)}</td>
          <td>{intl(`order_status_${formatValue(order, 'OrderStatus', '48')}`)}</td>
        </tr>
      )
    })
  }

  renderLoading () {
    if (this.props.historyOrderLoading) {
      return <Loading className="trade-data-query-table-loading"/>
    }
  }

  renderEmpty () {
    const { historyOrderLoading, historyOrderList } = this.props
    if (!historyOrderLoading && historyOrderList.size === 0) {
      return <p className="trade-data-query-table-no-data">{intl('no_data')}</p>
    }
  }

  renderPagination () {
    const {
      theme, currentContract, historyOrderLoading, historyOrderCurrentPage,
      historyOrderTotalPage, pollHistoryOrder, historyOrderList
    } = this.props
    if (historyOrderList.size !== 0 || !historyOrderLoading) {
      return (
        <Pagination
          theme={theme}
          className="trade-data-query-table-pagination"
          currentPage={historyOrderCurrentPage}
          totalPage={historyOrderTotalPage}
          onPageChange={(pageIndex) => { pollHistoryOrder(currentContract, pageIndex) }}/>
      )
    }
  }

  render () {
    return (
      <div className="trade-data-query-table-container">
        <table>
          <thead>
            <tr>
              <td>{intl('name')}</td>
              <td>{intl('direction')}</td>
              <td>{intl('order_time')}</td>
              <td>{intl('order_volume')}</td>
              <td>{intl('order_price')}</td>
              <td>{intl('trade_volume')}</td>
              <td>{intl('trade_average_price')}</td>
              <td>{intl('income')}</td>
              <td>{intl('fee')}</td>
              <td>{intl('status')}</td>
            </tr>
          </thead>
          <tbody>
            {this.renderTableContent()}
          </tbody>
        </table>
        {this.renderLoading()}
        {this.renderPagination()}
        {this.renderEmpty()}
      </div>
    )
  }
}

export default HistoryOrder
